package com.nc.delivery_project.server.domain.path_finder.old;

import java.util.*;

/**
 * Created by miroshnik on 2/3/2015.
 *
 */

public class DirectedGraph<T> implements Iterable<T> {

    private final Map<T, Map<T, Double>> mGraph = new HashMap<T, Map<T, Double>>();

    public boolean addNode(T node) {
        if (mGraph.containsKey(node))
            return false;

        mGraph.put(node, new HashMap<T, Double>());
        return true;
    }

    public void addEdge(T start, T dest, double length) {
        /* Confirm both endpoints exist. */
//        if (!mGraph.containsKey(start) || !mGraph.containsKey(dest))
//            throw new NoSuchElementException("Both nodes must be in the graph.");

        addNode(start);
        addNode(dest);

        /* Add the edge. */
        mGraph.get(start).put(dest, length);
    }

    public void removeEdge(T start, T dest) {
        /* Confirm both endpoints exist. */
        if (!mGraph.containsKey(start) || !mGraph.containsKey(dest))
            throw new NoSuchElementException("Both nodes must be in the graph.");

        mGraph.get(start).remove(dest);
    }

    public Map<T, Double> edgesFrom(T node) {
        /* Check that the node exists. */
        Map<T, Double> arcs = mGraph.get(node);
        if (arcs == null)
            throw new NoSuchElementException("Source node does not exist.");

        return Collections.unmodifiableMap(arcs);
    }

    public Iterator<T> iterator() {
        return mGraph.keySet().iterator();
    }
}